const app = getApp()
const WXAPI = require('../../wxapi/main');
const con = require("../../utils/data.js");

Page({
    data: {
        totalScoreToPay: 0,
        goodsList: [],
        isNeedLogistics: 0, // 是否需要物流信息
        allGoodsPrice: 0,
        yunPrice: 0,
        allGoodsAndYunPrice: 0,
        goodsJsonStr: "",
        choosedCouponId: '',
        orderType: "", //订单类型，购物车下单或立即支付下单，默认是购物车，
        pingtuanOpenId: undefined, //拼团的话记录团号
        mycurAddressData: [],
        hasNoCoupons: true,
        coupons: [],
        youhuijine: 0, //优惠券金额
        curCoupon: null, // 当前选择使用的优惠券
        allowSelfCollection: '0', // 是否允许到店自提
        peisongType: 'zq',
        oTotalprice: '', // 配送方式 kd,zq 分别表示快递/到店自取
        pPostage: 0,
        showCouponAction: false,
        buyNowInfo: '',
      brokerage:0,
        cid: '',
        discount: '', //折扣
        pSelfhelp:'0',
        oDeliverytypes:''
    },
    remind() {
        wx.showToast({
            title: '请选择配送地址',
        })
    },

    onShow: function() {
        let allowSelfCollection = wx.getStorageSync('ALLOW_SELF_COLLECTION')
        if (!allowSelfCollection || allowSelfCollection != '1') {
            allowSelfCollection = '0'
        }
        const that = this;
        let shopList = [];
        //立即购买下单
        if ("buyNow" == that.data.orderType) {
            var buyNowInfoMem = wx.getStorageSync('buyNowInfo');
            that.data.kjId = buyNowInfoMem.kjId;
            if (buyNowInfoMem && buyNowInfoMem.shopList) {
                shopList = buyNowInfoMem.shopList
            }
        } else {
            //购物车下单
            var shopCarInfoMem = wx.getStorageSync('shopCarInfo');
            that.data.kjId = shopCarInfoMem.kjId;
            if (shopCarInfoMem && shopCarInfoMem.shopList) {
                // shopList = shopCarInfoMem.shopList
                shopList = shopCarInfoMem.shopList.filter(entity => {
                    return entity.active;
                });
            }
        }
        that.setData({
            goodsList: shopList,
            allowSelfCollection: allowSelfCollection
        });
        console.log(that.data.goodsList, 65)
        that.initShippingAddress();
        that.totalPrice();
    },
    // 计算总额
    totalPrice: function() {
        var list = this.data.goodsList;
        var total = 0;
        var pPostage = this.data.pPostage || 0;
        var discount = this.data.discount || 1;
        console.log("pPostage" + pPostage);
        let totalScoreToPay = 0;
        for (var i = 0; i < list.length; i++) {
            var curItem = list[i];
            if (curItem.active) {
                // total += parseFloat(curItem.price) * discount * curItem.number + parseFloat(pPostage);
                if (this.data.orderType == 'buyNow' && curItem.comboPrice) {
                    total += (curItem.comboPrice * discount * curItem.number + parseFloat(pPostage));
                } else {
                    total += (curItem.price * discount * curItem.number + parseFloat(pPostage));
                }
                // total += (curItem.price * discount * curItem.number + parseFloat(pPostage));
                totalScoreToPay += curItem.score * curItem.number;
            }
        }
        total -= this.data.youhuijine
        this.data.goodsList.totalScoreToPay = totalScoreToPay;
        total = parseFloat(total.toFixed(2)); //js浮点计算bug，取两位小数精度
        this.setData({
                'oTotalprice': total,
                'amountPaid': total,
            })
            // debugger
        return total;
    },
    allSelect: function() {
        var list = this.data.goodsList.list;
        var allSelect = false;
        for (var i = 0; i < list.length; i++) {
            var curItem = list[i];
            if (curItem.active) {
                allSelect = true;
            } else {
                allSelect = false;
                break;
            }
        }
        return allSelect;
    },
    changeshowCouponAction() {
        this.setData({
            showCouponAction: !this.data.showCouponAction
        })
    },
    onChangeradio(event) {
        console.log(event, 106)
    },
    // bindChangeCoupon: function(e) {
    //     const selIndex = e.detail.value[0] - 1;
    //     if (selIndex == -1) {
    //         this.setData({
    //             youhuijine: 0,
    //             curCoupon: null
    //         });
    //         return;
    //     }
    //     // console.log("selIndex:" + selIndex);
    //     this.setData({
    //         youhuijine: this.data.coupons[selIndex].money,
    //         curCoupon: this.data.coupons[selIndex]
    //     });
    // },
    onCloseaction() {
        this.setData({ showCouponAction: false });
    },

    onClickradio(event) {
        const { id } = event.currentTarget.dataset;
        this.setData({
            cid: id
        })
        const { item } = event.currentTarget.dataset;
        console.log(id, 126)
        console.log(item, 126)
        if (!id) {
            this.setData({
                choosedCouponId: '',
                youhuijine: 0,
                curCoupon: null
            });
            this.totalPrice()
            return;
        }

        this.setData({
            youhuijine: item.money,
            curCoupon: item,
            choosedCouponId: id
        });
        console.log(this.data.youhuijine, 126)
        console.log(this.data.curCoupon, 126)

        this.totalPrice()
            // const selIndex = e.detail.value[0] - 1;
            // if (selIndex == -1) {
            //     this.setData({
            //         youhuijine: 0,
            //         curCoupon: null
            //     });
            //     return;
            // }
            // this.setData({
            //     youhuijine: this.data.coupons[selIndex].money,
            //     curCoupon: this.data.coupons[selIndex]
            // });
    },
    onLoad: function(e) {
      if (typeof (e.brokerage) != 'undefined'){
        var pPostage = e.pPostage;
        var pSelfhelp = e.pSelfhelp;
        var brokerage = e.brokerage
        console.log("pPostage" + pPostage);
        console.log("brokerage--" + brokerage);
        console.log("pSelfhelp:" + pSelfhelp);
        console.log("" + wx.getStorageSync("discount"));
        console.log("buyNowInfo", wx.getStorageSync('buyNowInfo'));
        this.setData({
          brokerage: brokerage
        })
      }
      this.setData({
            buyNowInfo: wx.getStorageSync('buyNowInfo'),
        })
        this.getMyCoupons(wx.getStorageSync('buyNowInfo').shopList[0].goodsId);
        let _data = {
            isNeedLogistics: 1
        }
        if (e.orderType) {
            _data.orderType = e.orderType
        }
        if (e.pingtuanOpenId) {
            _data.pingtuanOpenId = e.pingtuanOpenId
        }
      if (typeof (e.brokerage) != 'undefined') {
        _data.pPostage = pPostage;
        _data.pSelfhelp = pSelfhelp;
        _data.brokerage = brokerage;
      }
        if (wx.getStorageSync("discount") != null || wx.getStorageSync("discount") != "") {
            _data.discount = wx.getStorageSync("discount");
        } else {
            _data.discount = 0;
        }
        this.setData(_data);

    },

    getDistrictId: function(obj, aaa) {
        if (!obj) {
            return "";
        }
        if (!aaa) {
            return "";
        }
        return aaa;
    },

    createOrder: function(e) {
        var that = this;
        wx.showLoading()
        console.log([this.data.goodsList[0].propertyChildIds]);
        var oDeliverytypes = e.detail.value.oDeliverytypes;
        console.log("oDeliverytypes----"+oDeliverytypes);
        let remark = e.detail.value.remark;
        var shoppingTrolleyList = []
        this.data.goodsList.forEach(element => {
            if (element.sid) {
                //购物车提交
                shoppingTrolleyList.push({
                    "products": {
                        "pPid": element.goodsId
                    },
                    "sId": element.sid,
                    "sNum": element.number
                })
            } else {
                shoppingTrolleyList = {
                    "products": {
                        "pPid": element.goodsId
                    },
                    "aids": element.propertyChildIds,
                    "sNum": element.number,
                }
                if (element.comboPrice) {
                    shoppingTrolleyList.price = element.comboPrice
                }
              if (element.brokerage) {
                shoppingTrolleyList.brokerage = element.brokerage
              }
                if (element.comboSpec) {
                    shoppingTrolleyList.spec = element.comboSpec
                }
            }
        });
        console.log(shoppingTrolleyList, 218)
      console.log("specs:" + this.data.goodsList[0].label);
      var addrObj= this.data.mycurAddressData;
      console.log("addrObj" + addrObj.addr)
            // 提交订单
        wx.request({
                 url: 'https://www.brvpmusic.com/api/orderProduct/submitOrder',
          // url: 'http://172.20.10.8:8080/api/orderProduct/submitOrder',
                data: {
                    // "shoppingTrolleyList": [{
                    //     "products": {
                    //         "pPid": this.data.goodsList[0].goodsId
                    //     },
                    //     "aids": this.data.goodsList[0].propertyChildIds,
                    //     "sNum": this.data.goodsList[0].number
                    // }],
                    shoppingTrolleyList,
                    "customer": {
                        "openid": wx.getStorageSync('OpenId')
                    },
                  "oAddress": addrObj.provinceId + addrObj.cityId + addrObj.districtId+addrObj.addr,
                    "oLeavemessage": e.detail.value.remark,
                    "oTelephone": this.data.mycurAddressData.mobile,
                    "oDeliveryname": this.data.mycurAddressData.linkMan,
                    "oTotalprice": this.data.oTotalprice,
                     "specs": this.data.goodsList[0].label,
                    "oDeliverytypes":oDeliverytypes,
                    cId: this.data.cid,
                    "oCommission":this.data.brokerage,
                    amountPaid: this.data.oTotalprice
                    // amountPaid: this.data.oTotalprice + '.00'
                },

                method: 'POST',
                header: {
                    'Content-Type': 'application/json'
                },
                success: function(res) {
                    wx.hideLoading()
                    console.log('返回成功');
                    console.log(res.data);
                    if (res.data.status) {
                        wx.showToast({
                            title: '提交成功',
                        })
                        setTimeout(() => {
                            wx.setStorageSync('ordersIndextype', 0)
                            wx.switchTab({
                                url: "/pages/orders-list/index"
                            })
                        }, 1000);
                    } else {
                        wx.showToast({
                            title: res.data.message,
                            icon: 'none'
                        })
                    }


                    // that.setData({
                    //   mybanners: res.data.data,
                    // })
                },
                fail: function(res) {
                    wx.hideLoading()
                    console.log('返回失败');
                }
            })
            // var loginToken = wx.getStorageSync('token') // 用户登录 token
            // var remark = ""; // 备注信息
            // if (e) {
            //   remark = e.detail.value.remark; // 备注信息
            // }

        // let postData = {
        //   token: loginToken,
        //   goodsJsonStr: that.data.goodsJsonStr,
        //   remark: remark,
        //   peisongType: that.data.peisongType
        // };
        // if (that.data.kjId) {
        //   postData.kjid = that.data.kjId
        // }
        // if (that.data.pingtuanOpenId) {
        //   postData.pingtuanOpenId = that.data.pingtuanOpenId
        // }
        // if (that.data.isNeedLogistics > 0 && postData.peisongType == 'kd') {
        //   if (!that.data.curAddressData) {
        //     wx.hideLoading();
        //     wx.showModal({
        //       title: '错误',
        //       content: '请先设置您的收货地址！',
        //       showCancel: false
        //     })
        //     return;
        //   }
        //   if (postData.peisongType == 'kd') {
        //     postData.provinceId = that.data.curAddressData.provinceId;
        //     postData.cityId = that.data.curAddressData.cityId;
        //     if (that.data.curAddressData.districtId) {
        //       postData.districtId = that.data.curAddressData.districtId;
        //     }
        //     postData.address = that.data.curAddressData.address;
        //     postData.linkMan = that.data.curAddressData.linkMan;
        //     postData.mobile = that.data.curAddressData.mobile;
        //     postData.code = that.data.curAddressData.code;
        //   }      
        // }
        // if (that.data.curCoupon) {
        //   postData.couponId = that.data.curCoupon.id;
        // }
        // if (!e) {
        //   postData.calculate = "true";
        // }

        // WXAPI.orderCreate(postData).then(function (res) {
        //   if (res.code != 0) {
        //     // wx.showModal({
        //     //   title: '错误',
        //     //   content: res.msg,
        //     //   showCancel: false
        //     // })
        //     return;
        //   }

        //   if (e && "buyNow" != that.data.orderType) {
        //     // 清空购物车数据
        //     wx.removeStorageSync('shopCarInfo');
        //   }
        //   if (!e) {
        //     that.setData({
        //       totalScoreToPay: res.data.score,
        //       isNeedLogistics: res.data.isNeedLogistics,
        //       allGoodsPrice: res.data.amountTotle,
        //       allGoodsAndYunPrice: res.data.amountLogistics + res.data.amountTotle,
        //       yunPrice: res.data.amountLogistics
        //     });
        //     that.getMyCoupons();
        //     return;
        //   }
        //   WXAPI.addTempleMsgFormid({
        //     token: wx.getStorageSync('token'),
        //     type: 'form',
        //     formId: e.detail.formId
        //   })
        //   // 配置模板消息推送
        //   var postJsonString = {};
        //   postJsonString.keyword1 = {
        //     value: res.data.dateAdd,
        //     color: '#173177'
        //   }
        //   postJsonString.keyword2 = {
        //     value: res.data.amountReal + '元',
        //     color: '#173177'
        //   }
        //   postJsonString.keyword3 = {
        //     value: res.data.orderNumber,
        //     color: '#173177'
        //   }
        //   postJsonString.keyword4 = {
        //     value: '订单已关闭',
        //     color: '#173177'
        //   }
        //   postJsonString.keyword5 = {
        //     value: '您可以重新下单，请在30分钟内完成支付',
        //     color: '#173177'
        //   }
        //   WXAPI.sendTempleMsg({
        //     module: 'order',
        //     business_id: res.data.id,
        //     trigger: -1,
        //     postJsonString: JSON.stringify(postJsonString),
        //     template_id: 'mGVFc31MYNMoR9Z-A9yeVVYLIVGphUVcK2-S2UdZHmg',
        //     type: 0,
        //     token: wx.getStorageSync('token'),
        //     url: 'pages/index/index'
        //   })
        //   postJsonString = {};
        //   postJsonString.keyword1 = {
        //     value: '您的订单已发货，请注意查收',
        //     color: '#173177'
        //   }
        //   postJsonString.keyword2 = {
        //     value: res.data.orderNumber,
        //     color: '#173177'
        //   }
        //   postJsonString.keyword3 = {
        //     value: res.data.dateAdd,
        //     color: '#173177'
        //   }
        //   WXAPI.sendTempleMsg({
        //     module: 'order',
        //     business_id: res.data.id,
        //     trigger: 2,
        //     postJsonString: JSON.stringify(postJsonString),
        //     template_id: 'Arm2aS1rsklRuJSrfz-QVoyUzLVmU2vEMn_HgMxuegw',
        //     type: 0,
        //     token: wx.getStorageSync('token'),
        //     url: 'pages/order-details/index?id=' + res.data.id
        //   })
        //   // 下单成功，跳转到订单管理界面
        //   wx.redirectTo({
        //     url: "/pages/order-list1/index"
        //   });
        // })
    },
    initShippingAddress: function() {
        // 保存到自己的后台
        console.log(con.index_getaddress, 426);
        var that = this;
        wx.request({
            url: con.index_getaddress,
            method: 'GET',
            data: {
                openid: wx.getStorageSync('OpenId'),
            },
            header: {
                'Content-Type': 'application/json'
            },
            success: function(res) {
                console.log(res.data);
                console.log(con.index_getaddress, 439);
                console.log('返回成功');
                that.setData({
                    mycurAddressData: res.data.body
                })


            },
            fail: function(res) {
                console.log('返回失败', res);
                console.log(con.index_getaddress, 449);

            }
        })


        // ---------------
        var that = this;
        WXAPI.defaultAddress(wx.getStorageSync('token')).then(function(res) {
            if (res.code == 0) {
                that.setData({
                    curAddressData: res.data
                });
            } else {
                that.setData({
                    curAddressData: null
                });
            }
            that.processYunfei();
        })
    },
    processYunfei: function() {
        var that = this;
        var goodsList = this.data.goodsList;
        var goodsJsonStr = "[";
        var isNeedLogistics = 0;
        var allGoodsPrice = 0;


        let inviter_id = 0;
        let inviter_id_storge = wx.getStorageSync('referrer');
        if (inviter_id_storge) {
            inviter_id = inviter_id_storge;
        }
        for (let i = 0; i < goodsList.length; i++) {
            let carShopBean = goodsList[i];
            if (carShopBean.logistics) {
                isNeedLogistics = 1;
            }
            // allGoodsPrice += carShopBean.price * carShopBean.number;
            if (this.data.orderType == 'buyNow' && carShopBean.comboPrice) {
                allGoodsPrice += carShopBean.comboPrice * carShopBean.number;
            } else {
                allGoodsPrice += carShopBean.price * carShopBean.number;
            }


            var goodsJsonStrTmp = '';
            if (i > 0) {
                goodsJsonStrTmp = ",";
            }

            goodsJsonStrTmp += '{"goodsId":' + carShopBean.goodsId + ',"number":' + carShopBean.number + ',"propertyChildIds":"' + carShopBean.propertyChildIds + '","logisticsType":0, "inviter_id":' + inviter_id + '}';
            goodsJsonStr += goodsJsonStrTmp;


        }
        goodsJsonStr += "]";
        //console.log(goodsJsonStr);
        that.setData({
            isNeedLogistics: isNeedLogistics,
            goodsJsonStr: goodsJsonStr
        });
    },
    addAddress: function() {
        wx.navigateTo({
            url: "/pages/address-add/index"
        })
    },
    selectAddress: function() {
        wx.navigateTo({
            url: "/pages/select-address/index"
        })
    },
    getMyCoupons(pPid) {
        var that = this;
        WXAPI.myCoupons({
            cOpenid: wx.getStorageSync('OpenId'),
            pPid
        }).then((res) => {
            console.log(res, 459)
            if (res.body.length > 0) {
                // cId:优惠券id
                // cName：优惠券名称 String
                // cDistributor：优惠券发放人 String
                // cIshave：优惠券面值 Decimal
                // cIssue：优惠券发布数量 int 
                // cResidue：剩余优惠券数量 int 
                // cBegin:优惠券开始(添加时间) Date
                // cExit：优惠券结束日期 Date
                // cNum：优惠券领取后-有效天数(單位:天) int
                // cLowest：最低金额限度 Decimal
                // cDiejia:是否可以叠加使用(0:不可以1：可以) byte
                // cIsdel:是否有效(0:无效,1:有效) byte
                var coupons = res.body.filter(entity => {
                    var price = 0
                    this.data.buyNowInfo.shopList.forEach(element => {
                        if (this.data.orderType == 'buyNow' && element.comboPrice) {
                            price += (element.comboPrice * element.number)
                        } else {
                            price += (element.price * element.number)
                        }
                        // price += element.price
                    });
                    if (this.data.buyNowInfo.shopList.length > 1) {
                        //多个商品不能使用优惠券
                        price = 0
                    }
                    console.log(price, 459)
                    console.log(entity.cIsdel == 1, 459)
                    console.log(entity.cLowest <= price, 459)
                    console.log(entity.cResidue > 0, 459)
                    console.log(new Date(entity.cExit) > new Date(), 459)
                  // var screen = (entity.cIsdel == 1) &&
                  //     (entity.cLowest <= price) &&
                  //     (entity.cResidue > 0) && (new Date(entity.cExit) > new Date())
                    var screen = (entity.cLowest <= price) 

                    if (screen) {
                        entity.money = entity.cIshave
                        entity.name = entity.cName
                        entity.id = entity.cId
                    }

                    return screen
                });
                coupons.push({
                        money: '',
                        name: '不使用优惠券',
                        id: ''
                    })
                    // var coupons = res.data.filter(entity => {
                    //     return entity.moneyHreshold <= that.data.allGoodsAndYunPrice;
                    // });
                if (coupons.length > 0) {
                    that.setData({
                        hasNoCoupons: false,
                        coupons: coupons
                    });
                }
            }
        })
    },
    // bindChangeCoupon: function (e) {
    //   const selIndex = e.detail.value[0] - 1;
    //   if (selIndex == -1) {
    //     this.setData({
    //       youhuijine: 0,
    //       curCoupon: null
    //     });
    //     return;
    //   }
    //   // console.log("selIndex:" + selIndex);
    //   this.setData({
    //     youhuijine: this.data.coupons[selIndex].money,
    //     curCoupon: this.data.coupons[selIndex]
    //   });
    // },
    radioChange(e) {
        this.setData({
            peisongType: e.detail.value
        })
    }
})